package com.aruba.flowapplyapplication

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.aruba.flowapplyapplication.adapter.ArticleAdapter
import com.aruba.flowapplyapplication.databinding.FragmentArticleBinding
import com.aruba.flowapplyapplication.viewmodel.ArticleViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class ArticleFragment : Fragment() {

    private val articleViewModel by lazy { ArticleViewModel() }

    private val articleAdapter by lazy { ArticleAdapter() }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val fragmentArticleBinding = DataBindingUtil.inflate<FragmentArticleBinding>(
            inflater,
            R.layout.fragment_article,
            container,
            false
        )

        //绑定viewmodel
        fragmentArticleBinding.articleViewModel = articleViewModel
        //配置recyclerview
        fragmentArticleBinding.recyclerview.adapter = articleAdapter
        fragmentArticleBinding.recyclerview.layoutManager = LinearLayoutManager(requireContext())

        //设置LiveData
        fragmentArticleBinding.lifecycleOwner = viewLifecycleOwner

        //对edittext文本进行监听
        articleViewModel.searchText.observe(viewLifecycleOwner) {
            articleViewModel.getArticle()
        }
        //对服务器返回list的变化进行监听
        articleViewModel.articleList.observe(viewLifecycleOwner) {
            articleAdapter.setData(it)
        }

        return fragmentArticleBinding.root
    }

}